interface TreeConfig<T, K extends keyof T, C extends string = "children"> {
	id: K;
	parentId: K;
	children: C; // children 是一个字符串字段名，通过泛型传入，默认为 "children"
}

type TreeNode<T, K extends keyof T, C extends string = "children"> = T & {
	[key in C]: TreeNode<T, K, C>[]; // 动态添加 children 字段
};

interface HandleTreeParams<
	T,
	K extends keyof T,
	C extends string = "children",
> {
	data: T[];
	id?: K;
	parentId?: K;
	children?: C; // children 是一个字符串字段名，通过泛型传入，默认为 "children"
}
/**
 * 构造树型结构数据
 * @param {HandleTreeParams<T, K, C>} params 参数对象
 * @param {T[]} params.data 数据源
 * @param {K} [params.id='id'] id字段 默认 'id'
 * @param {K} [params.parentId='parentId'] 父节点字段 默认 'parentId'
 * @param {C} [params.children='children'] 孩子节点字段 默认 'children'
 * @returns {TreeNode<T, K, C>[]} 树型结构数据
 */
export function handleTree<T, K extends keyof T, C extends string = "children">(
	params: HandleTreeParams<T, K, C>
): TreeNode<T, K, C>[] {
	const { data, id, parentId, children } = params;

	const config: TreeConfig<T, K, C> = {
		id: id || ("id" as K),
		parentId: parentId || ("parentId" as K),
		children: children || ("children" as C), // 默认值为 "children"
	};

	const childrenListMap: { [key: string]: T[] } = {};
	const nodeIds: { [key: string]: T } = {};
	const tree: TreeNode<T, K, C>[] = [];

	// 构建 childrenListMap 和 nodeIds
	for (const d of data) {
		const parentIdValue = d[config.parentId] as unknown as string;
		if (childrenListMap[parentIdValue] == null) {
			childrenListMap[parentIdValue] = [];
		}
		nodeIds[d[config.id] as unknown as string] = d;
		childrenListMap[parentIdValue].push(d);
	}

	// 找到根节点
	for (const d of data) {
		const parentIdValue = d[config.parentId] as unknown as string;
		if (nodeIds[parentIdValue] == null) {
			tree.push(d as TreeNode<T, K, C>);
		}
	}

	// 递归添加 children 字段
	for (const t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o: TreeNode<T, K, C>) {
		const childrenKey = config.children;
		const idValue = o[config.id] as unknown as string;

		if (childrenListMap[idValue] !== null) {
			// 修复：明确将 childrenListMap[idValue] 断言为 TreeNode<T, K, C>[C]
			o[childrenKey] = childrenListMap[idValue] as unknown as TreeNode<
				T,
				K,
				C
			>[C];
		}
		if (o[childrenKey]) {
			for (const c of o[childrenKey]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}
